#include "line.h"
#include "ui_line.h"
#include <QLineSeries>
#include<QFileDialog>
#include<QFile>
#include<ActiveQt/QAxObject>
#include <QLine>
//先建立 QChart 对象
//建立 QLineSeries 或者其他的 Series
//建立 QValueAxis 或者其他的 Axis 对象
//QChart 对象 用 addSeries 添加 QLineSeries 对象
//QLineSeries 用 attachAxis 绑定 Axis 对象
//给 QLineSeries 对象添加数据
Line::Line(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Line)
{
    ui->setupUi(this);
    setWindowTitle("线状图");
    setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    connect(ui->back,&QPushButton::clicked,[=](){
        emit back();
    });
    //是否展示网格
    connect(ui->isgrid,&QCheckBox::stateChanged,[=](int x){
        this->grid=(x==2);
    });
    //是否突起
    connect(ui->tup,&QCheckBox::stateChanged,[=](int x){
        this->tu=(x==2);
    });
    ui->xname->setPlaceholderText("请输入X轴名称");
    ui->yname->setPlaceholderText("请输入Y轴名称");
    //设置默认选择
    ui->isgrid->setChecked(1);
    ui->tup->setChecked(1);
    ui->flod->setChecked(1);

    //下面和bar的设置差不多
    QStringList LineChartHeader;
    LineChartHeader << "类别 1" << "类别 2" << "类别 3";
    ui->tableWidget->setColumnCount(4);
    ui->tableWidget->setRowCount(5);

    ui->tableWidget->setItem(0,0,new QTableWidgetItem("输入图表标题"));
    ui->tableWidget->setItem(1,0,new QTableWidgetItem("该列填X坐标"));
    for (int column = 0; column < LineChartHeader.size() ; column++)
        ui->tableWidget->setItem(0, column+1, new QTableWidgetItem(LineChartHeader.at(column)));

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setVisible(false);
    ui->tableWidget->verticalHeader()->setVisible(false);

    ui->tableWidget->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui->tableWidget->setAlternatingRowColors(true);
}

Line::~Line()
{
    delete ui;
}

void Line::on_createchart_clicked()
{
    //处理数据
    int colCount = ui->tableWidget->columnCount();
    int rowCount = ui->tableWidget->rowCount();

    for(int i=0;i<rowCount;i++)
        for(int j=0;j<colCount;j++){
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item==nullptr)
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
        }

    QStringList lineseriesData;//存名字
    double numData[rowCount - 1][colCount - 1];//y值
    double numx[rowCount-1];//x值
    double minyvalue=numData[0][0],maxyvalue=numData[0][0];//寻找y轴最大最小值以便设置范围
    //获取每条线的信息
    for (int col = 1; col < colCount; col++)
    {
        lineseriesData << ui->tableWidget->item(0, col)->text();
        for (int row = 1; row < rowCount; row++)
        {
            numData[row - 1][col - 1] = ui->tableWidget->item(row, col)->text().toDouble();
            numx[row - 1] = ui->tableWidget->item(row,0)->text().toDouble();
        }
    }

    //先初始化chart，if语句再分流
    QChart *chart = new QChart();

    chart->createDefaultAxes();
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->setTitle(ui->tableWidget->item(0, 0)->text());
    chart->setTitleFont(QFont("微软雅黑"));

    QValueAxis *axisY = new QValueAxis;
    chart->addAxis(axisY, Qt::AlignLeft);
    axisY->setLineVisible(true); //设置轴线和刻度线可见性
    axisY->setGridLineVisible(grid);
    axisY->setTitleText(ui->yname->text());

    QValueAxis *axisX = new QValueAxis;
    chart->addAxis(axisX,Qt::AlignBottom);
    axisX->setLineVisible(true);
    axisX->setGridLineVisible(grid);
    axisX->setTickCount(rowCount-1);
    axisX->setTitleText(ui->xname->text());

    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignTop);

    QChartView *chartView = new QChartView(chart);
    chartView->setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    chartView->setWindowTitle("线状图");
    chartView->setRenderHint(QPainter::Antialiasing);
    chartView->resize(1000, 800);

    if(ui->flod->isChecked()){
        QLineSeries *series[colCount - 1];//线条
        for (int i = 0; i < colCount - 1; i++)
        {
            series[i] = new QLineSeries();
            for (int j = 0; j < rowCount - 1; j++)
            {
                series[i]->append(numx[j], numData[j][i]);
                minyvalue=minyvalue<numData[j][i]?minyvalue:numData[j][i];
                maxyvalue=maxyvalue>numData[j][i]?maxyvalue:numData[j][i];
            }
            series[i]->setName(lineseriesData.at(i));
        }
        axisY->setRange(minyvalue,maxyvalue);//设置y轴
        for (int i = 0; i < colCount - 1; i++)
            chart->addSeries(series[i]);//
        for (int i = 0; i < colCount - 1; i++)
        {
            series[i]->attachAxis(axisY);
            series[i]->attachAxis(axisX);
            series[i]->setPointsVisible(tu);//是否凸点
        }
        chartView->show();
    }
    else if(ui->curve->isChecked())
    {
        QSplineSeries *series[colCount - 1];//线条
        for (int i = 0; i < colCount - 1; i++)
        {
            series[i] = new QSplineSeries();
            for (int j = 0; j < rowCount - 1; j++)
            {
                series[i]->append(numx[j], numData[j][i]);
                minyvalue=minyvalue<numData[j][i]?minyvalue:numData[j][i];
                maxyvalue=maxyvalue>numData[j][i]?maxyvalue:numData[j][i];
            }
            series[i]->setName(lineseriesData.at(i));
        }
        axisY->setRange(minyvalue*0.8,maxyvalue*1.2);//设置y轴范围，避免有段曲线无法显示
        for (int i = 0; i < colCount - 1; i++)
            chart->addSeries(series[i]);
        for (int i = 0; i < colCount - 1; i++)
        {
            series[i]->attachAxis(axisY);
            series[i]->attachAxis(axisX);
            series[i]->setPointsVisible(tu);//是否凸点
        }
        chartView->show();
    }
}

void Line::on_addc_clicked()
{
    int count = ui->tableWidget->columnCount();
    ui->tableWidget->insertColumn(count);
    ui->tableWidget->setItem(0, count, new QTableWidgetItem("类别 " + QString::number(count)));
}

void Line::on_deletec_clicked()
{
    int count = ui->tableWidget->columnCount();
    if (count > 2)
        ui->tableWidget->setColumnCount(count - 1);
    else
        QMessageBox::warning(this, "警告", "至少要有一种类别");
}

void Line::on_addr_clicked()
{
    int count = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(count);
}

void Line::on_deleter_clicked()
{
    int count = ui->tableWidget->rowCount();
    if (count > 3)
        ui->tableWidget->setRowCount(count - 1);
    else
        QMessageBox::warning(this, "警告", "至少要有两组数据");
}

void Line::on_pushButton_clicked()
{
    int rowcount=ui->tableWidget->rowCount();
    int columncount=ui->tableWidget->columnCount();
    for(int i=0;i<rowcount;i++)
        for(int j=0;j<columncount;j++){
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item==nullptr)
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
            else
                ui->tableWidget->item(i,j)->setText("");
        }
    ui->tableWidget->item(0,0)->setText("输入图表标题");
    ui->tableWidget->item(1,0)->setText("该列填X坐标");
    for(int i=1;i<columncount;i++)
        ui->tableWidget->item(0,i)->setText("类别 " + QString::number(i));
}

void Line::on_pushButton_2_clicked()
{
        QString fileName=QFileDialog::getOpenFileName(this,"读取","C:\\Users","(*.xlsx)");
        if(fileName.isEmpty())
            return;
        fileName=QDir::toNativeSeparators(fileName);

        QAxObject* excel = new QAxObject("Excel.Application", this);
        QAxObject* workbooks = excel->querySubObject("Workbooks");
        QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", fileName);
        QAxObject* sheets = workbook->querySubObject("Sheets");
        QAxObject* sheet = sheets->querySubObject("Item(int)", 1); // 第一个工作表
        QAxObject* usedRange = sheet->querySubObject("UsedRange");
        QAxObject* rows = usedRange->querySubObject("Rows");
        QAxObject* columns = usedRange->querySubObject("Columns");

        int rowCount = rows->property("Count").toInt();
        int columnCount = columns->property("Count").toInt();

        ui->tableWidget->setRowCount(rowCount+1);
        ui->tableWidget->setColumnCount(columnCount);

        for(int i=0;i<ui->tableWidget->rowCount();i++)
            for(int j=0;j<ui->tableWidget->columnCount();j++){
                QTableWidgetItem* item = ui->tableWidget->item(i, j);
                if(item==nullptr)
                    ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
            }

        for (int row = 1; row <= rowCount; ++row) {
            for (int column = 1; column <= columnCount; ++column) {
                QAxObject* cell = sheet->querySubObject("Cells(int,int)", row, column);
                QString value = cell->property("Value").toString();
                ui->tableWidget->item(row, column - 1)->setText(value);
            }
        }

        workbook->dynamicCall("Close()");
        excel->dynamicCall("Quit()");
}
